package com.fengye.cloud.reactive.service.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 *
 * @author sky
 * @date 2021年06月02日 10:35 上午
 */
@RestController
@RequestMapping("/v1/user")
public class UserController {

    // @Autowired
    // private HttpServerRequest request;
    @Autowired
    private WebClient.Builder webClientBuilder;


    @HystrixCommand(commandProperties = {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000")})
    @GetMapping("/{id}")
    public Mono<String> getAccount(@PathVariable String id) {
        return webClientBuilder.build().get().uri("http://account-service/v1/account/{id}", id)
                .retrieve().bodyToMono(String.class);
    }

    private Flux<String> getAccountsFallback() {
        List<String> fallbackList = new ArrayList<>();

        fallbackList.add("error,fallback");

        return Flux.fromIterable(fallbackList);
    }

    @HystrixCommand(
            fallbackMethod = "getAccountsFallback",
            threadPoolKey = "accountThreadPool",
            threadPoolProperties = {
                    @HystrixProperty(name = "coreSize", value = "30"),
                    @HystrixProperty(name = "maxQueueSize", value = "10")
            },
            commandProperties = {
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "5000")
            }
    )
    @GetMapping("/accounts")
    public Flux<String> getAccounts() {
        Random random = new Random();
        int nextInt = random.nextInt(10);
        System.out.println(nextInt);
        if (nextInt > 5) {
            throw new RuntimeException("嘿嘿出错拉");
        }
        // TODO: 具体的业务逻辑
        String[] accounts = new String[]{"account1", "account2"};
        return Flux.fromArray(accounts);
    }
}
